package com.tuling.signalling;

import io.netty.channel.Channel;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class MatchTools {

    public static Map<String, Channel> streamerMapIdle = new ConcurrentHashMap<>();

    public static Map<String, Channel> streamerMapBusy = new ConcurrentHashMap<>();

    public static Map<String, Channel> playerMap = new ConcurrentHashMap<>();

    /**
     * streamerId -> playerId
     */
    public static Map<String, String> matchSpMap = new ConcurrentHashMap<>();

    public static Map<String, String> matchPsMap = new ConcurrentHashMap<>();

    public static String getIdleStreamerId() {
        Set<String> idles = streamerMapIdle.keySet();
        String streamerId = "";
        for (String id : idles) {
            streamerId = id;
            break;
        }
        return streamerId;
    }

    public static void matchFirst(String playerId) {
        match(getIdleStreamerId(), playerId);
    }

    public static void match(String streamerId, String playerId) {
        matchSpMap.put(streamerId, playerId);
        matchPsMap.put(playerId, streamerId);
        Channel busy = streamerMapIdle.remove(streamerId);
        streamerMapBusy.put(streamerId, busy);
    }

    public static void delByStreamer(String streamerId) {
        String playerId = matchSpMap.remove(streamerId);
        matchPsMap.remove(playerId);
    }

    public static void addIdleStreamer(String streamerId, Channel channel){
        MatchTools.streamerMapIdle.put(streamerId, channel);
    }

    public static void addPlayer(String playerId, Channel channel){
        MatchTools.playerMap.put(playerId, channel);
    }

    public static void removeStreamer(String streamerId){
        Channel idleChannel = MatchTools.streamerMapIdle.remove(streamerId);
        // 如果是空闲的流断掉
        if (idleChannel != null) {
            idleChannel.close();
        } else {
            // 如果是忙碌的流断掉
            Channel busyChannel = MatchTools.streamerMapBusy.remove(streamerId);
            if (busyChannel != null) {
                busyChannel.close();
            }
        }

    }

}
